<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表单名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入表单名" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="表单状态" clearable size="small">
          <el-option v-for="dict in dict.type.form_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['bpm:form:create']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="数据库名" align="center" prop="name">
        <template slot-scope="scope">
          <el-tag type="info" @click="handleDetail(scope.row)">{{ scope.row.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="表单名" align="center" prop="remark" />
      <el-table-column label="开启状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.form_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail(scope.row)" v-hasPermi="['bpm:form:query']">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleSubmit(scope.row)" v-hasPermi="['bpm:form:delete']">数据提交</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['bpm:form:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['bpm:form:delete']">删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['power:role:edit']">
            <span class="el-dropdown-link"> <i class="el-icon-d-arrow-right el-icon--right"></i>更多 </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDetail" icon="el-icon-edit" v-hasPermi="['power:role:edit']">详情</el-dropdown-item>
              <el-dropdown-item command="handleSubmit" icon="el-icon-upload2" v-hasPermi="['bpm:form:submit']">数据提交</el-dropdown-item>
              <el-dropdown-item command="systemMenuList" icon="el-icon-menu" v-hasPermi="['bpm:form:menu']">添加菜单</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!--表单配置详情-->
    <el-dialog title="表单详情" :visible.sync="detailOpen" width="50%" append-to-body>
      <div class="test-form">
        <parser :key="new Date().getTime()" :form-conf="detailForm" @submit="submitForm" />
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="menuShow" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect v-model="form.parentId" :options="menuOptions" :normalizer="normalizer" :show-count="true" placeholder="选择上级菜单" />
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="form.menuType != 'F'">
            <el-form-item label="菜单图标">
              <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['iconSelect'].reset()">
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>
                  <svg-icon v-if="form.icon" slot="prefix" :icon-class="form.icon" class="el-input__icon" style="height: 32px; width: 16px" />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType == 'C'">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                是否缓存
              </span>
              <el-radio-group v-model="form.isCache">
                <el-radio label="0">缓存</el-radio>
                <el-radio label="1">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 'F'">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                显示状态
              </span>
              <el-radio-group v-model="form.visible">
                <el-radio v-for="dict in dict.type.sys_show_hide" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 'F'">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                菜单状态
              </span>
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormMenu">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteForm, getForm, getFormPage, publicSubmit } from '@/api/bpm/form'
import { getInfo } from '@/api/login'
import Parser from '@/components/parser/Parser'
import { decodeFields } from '@/utils/formGenerator'
import { listMenu, addMenu, updateMenu } from '@/api/system/menu'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import IconSelect from '@/components/IconSelect'
export default {
  name: 'Form',
  dicts: ['form_status', 'sys_show_hide', 'sys_normal_disable'],
  components: {
    Parser,
    Treeselect,
    IconSelect
  },
  data() {
    return {
      form: {},
      // 表单校验
      rules: {
        menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
        orderNum: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }]
      },
      menuShow: false,
      menuOptions: [],
      username: '',
      // 弹出层标题
      title: '',
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工作流的列表
      list: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        name: null
      },
      // 表单详情
      detailOpen: false,
      neRow: 0,
      detailForm: {
        fields: []
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 提交按钮 */
    submitFormMenu() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.menuId != undefined) {
            updateMenu(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.menuShow = false
              this.getList()
            })
          } else {
            addMenu(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.menuShow = false
              this.getList()
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.menuShow = false
      this.reset()
    },
    // 选择图标
    selected(name) {
      this.form.icon = name
    },
    reset() {
      this.form = {
        menuId: undefined,
        parentId: 0,
        menuName: undefined,
        icon: undefined,
        menuType: 'M',
        orderNum: undefined,
        isFrame: '1',
        isCache: '0',
        visible: '0',
        status: '0'
      }
      this.resetForm('form')
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      }
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu().then((response) => {
        this.menuOptions = []
        const menu = { menuId: 0, menuName: '主类目', children: [] }
        menu.children = this.handleTree(response.data, 'menuId')
        this.menuOptions.push(menu)
      })
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleSubmit':
          this.handleSubmit(row)
          break
        case 'handleDetail':
          this.handleDetail(row)
          break
        case 'systemMenuList':
          this.systemMenuList(row)
          break
        default:
          break
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      // 处理查询参数
      let params = { ...this.queryParams }
      // 执行查询
      getFormPage(params).then((response) => {
        this.list = response.data.list
        this.total = response.data.total

        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.neRow = row
      getForm(row.id).then((response) => {
        // 设置值
        const data = response.data
        this.detailForm = {
          ...JSON.parse(data.conf),
          fields: decodeFields(data.fields)
        }

        // 弹窗打开
        this.detailOpen = true
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: '/bpm/form/edit'
      })
    },
    handleSubmit(row) {
      this.$router.push({
        path: '/bpm/form/submit',
        query: {
          formId: row.id
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        path: '/bpm/form/edit',
        query: {
          formId: row.id
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal
        .confirm('是否确认删除工作表单的编号为"' + id + '"的数据项?')
        .then(function () {
          return deleteForm(id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    submitForm(params) {
      // getInfo().then((response) => {
      //   params.values = { ...params.values, ...{ createBy: response.user.userName } }
      //   publicSubmit('/Sleepfish/save', 'post', params).then((response) => {
      //     this.detailOpen = false
      //   })
      // })
    },
    systemMenuList(row) {
      this.reset()
      this.getTreeselect()
      this.form.parentId = 8
      this.form.menuType = 'C'
      this.form.isFrame = '1'
      this.form.component = 'bpm/form/show'
      this.form.perms = 'bpm:form:show'
      this.form.path = 'form/submit?formId=' + row.id
      this.menuShow = true
      this.title = '添加菜单'
    }
  }
}
</script>
